package com.azxc.rapid.plus.resource.timer;

import com.azxc.rapid.core.oss.enums.OssStatusEnum;
import com.azxc.rapid.core.tool.api.R;
import com.azxc.rapid.plus.resource.entity.AttachCleanLog;
import com.azxc.rapid.plus.resource.service.IAttachCleanLogService;
import com.azxc.rapid.resource.builder.oss.OssBuilder;
import com.azxc.rapid.resource.entity.Oss;
import com.azxc.rapid.resource.service.IOssService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @description: 通过定时器执行附件的删除
 * @author: SQG
 * @create: 2022-08-23 10:04
 **/
@AllArgsConstructor
@Component
@Slf4j
public class AttachCleanJob {
	private final OssBuilder ossBuilder;

	private final IOssService ossService;

	private final IAttachCleanLogService attachCleanLogService;

	/**
	 * 用定时任务每天凌晨00:00:00执行需要清理的资源文件
	 *
	 * @return
	 */
//	@XxlJob("attachCleanHandler")
	@Scheduled(cron = "0 0 0 * * ?")
	public R<String> attachCleanHandler() {
		log.info("创建任务start...................");
		List<AttachCleanLog> list = attachCleanLogService.list(Wrappers.<AttachCleanLog>lambdaQuery().eq(AttachCleanLog::getIsDeleted, 0));
		list.stream().forEach(
			e -> {
				LambdaQueryWrapper<Oss> lqw = Wrappers.<Oss>query().lambda().eq(Oss::getTenantId, e.getTenantId()).eq(Oss::getStatus, OssStatusEnum.ENABLE.getNum());
				Oss oss = ossService.getOne(lqw);
				if (oss != null) {
					//删除资源服务器的信息
					ossBuilder.template(e.getTenantId(), oss.getOssCode()).removeFile(e.getName());
				}
				//删除附件表中的记录
				attachCleanLogService.removeById(e.getId());
			}
		);
		log.info("创建任务end................");
		return R.status(true);
	}


}
